package com.yyfax.ph.home.imageupload;

import android.text.TextUtils;
import com.yyfax.common.CLog;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.common.imageselector.bean.ImageBean;
import com.yyfax.ph.common.imageselector.utils.FileUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 已上传的图片Id管理，单例，图片上传到后台并返回id，最后把确定提交的图片id传给后台
 */
public class ImageIdManager {

	/**
	 * 新上传的图片集合和已上传的图片集合对比，并返回有效上传的图片集合(取两个图片集合的交集)
	 */
	public static ArrayList<ImageBean> getImageBeans(ArrayList<String> newPaths, ArrayList<ImageBean> mImageBeans) {
		CLog.i("ImageIdManager", "getDataSet-->" + newPaths.toString());
		CLog.i("ImageIdManager", "mArguments.imageBeans-->" + mImageBeans.toString());
		ArrayList<ImageBean> newImageBeans = new ArrayList<>();
		for (String newPath : newPaths) {
			for (ImageBean imageBean : mImageBeans) {
				if (imageBean.newPath.equals(newPath)) {
					newImageBeans.add(imageBean);
					break;
				}
			}
		}
		return newImageBeans;
	}

	public static void clearId() {
		releaseCacheImages();
	}

	private static void deleteFile(File dir) {
		if (dir == null || !dir.exists() || dir.isFile()) {
			return;
		}

		boolean status;
		if (dir.isDirectory()) {
			File[] files = dir.listFiles();
			if (files != null && files.length > 0) {
				for (File file : files) {
					if (file.isFile()) {
						status = file.delete();
						if (!status)
							CLog.i("ImageIdManager", "failure to delete file: " + dir.getPath());
					} else if (file.isDirectory()) {
						deleteFile(file); // 递归
					}
				}
			}
		}

		status = dir.delete();
		CLog.i("ImageIdManager", "delete directory" + dir.getPath() + " is " + status);
	}

	private static void releaseCacheImages() {
		GlobalVariableConfig.getExecutorService().execute(new Runnable() {
			@Override
			public void run() {
				File file = new File(FileUtils.DEFAULT_SAVE_IMAGE_PATH_UPLOAD);
				deleteFile(file);
			}
		});
	}

	public static List<String> getImageIdList(List<ImageBean> list) {
		List<String> fileNames = new ArrayList<>();
		if (null != list) {
			for (ImageBean imageBean : list) {
				if (!TextUtils.isEmpty(imageBean.imageId))
					fileNames.add(imageBean.imageId);
			}
		}
		CLog.i("ImageIdManager", "已上传图片single=" + fileNames.toString());
		return fileNames;
	}

	public static List<String> getMergeImageIdList(List<ImageBean> list1, List<ImageBean> list2) {
		List<String> fileNames = new ArrayList<>();
		if (null != list1) {
			for (ImageBean imageBean : list1) {
				if (!TextUtils.isEmpty(imageBean.imageId))
					fileNames.add(imageBean.imageId);
			}
		}
		if (null != list2) {
			for (ImageBean imageBean : list2) {
				if (!TextUtils.isEmpty(imageBean.imageId))
					fileNames.add(imageBean.imageId);
			}
		}
		CLog.i("ImageIdManager", "已上传图片merge=" + fileNames.toString());
		return fileNames;
	}
}
